import React, { Component } from 'react';
import './songdetail.css'
// 引入轮播图的组件
import { Swiper, SwiperSlide } from 'swiper/react';
// 引入轮播图的样式
import 'swiper/swiper-bundle.css';
import 'swiper/swiper-bundle.min.css';
class SongDetail extends Component {
  constructor() {
    super()
    // this.audio = React.createRef()
    this.state = {
      imgList: [],
      songUrl: '',
      isPlay: false,
      // 歌词（对象）
      lyric: {},
      height: 0
    }
  }
  componentWillMount() {
    this.setState({
      songUrl: 'https://music.163.com/song/media/outer/url?id=' + this.props.match.params.id + '.mp3'
    })
    this.$axios.get('/api/lyric?id=' + this.props.match.params.id)
      .then(res => {
        this.setState({
          lyric: this.formatLrc(res.data.lrc.lyric)
        })
      })
      .catch(err => {
        console.log(err);
      })
  }
  // 格式化歌词
  formatLrc(str) {
    let obj = {};
    // 正则表达式,方括号中是时间，匹配方括号中的内容作为key，剩下的是value
    let reg = /\[(.*)](.*)/g;
    str.replace(reg, (a, b, c) => {
      // a是一整项，b是方括号的内容，c是方括号后面的内容
      // console.log(1,a);
      // console.log(2,b);
      // console.log(3,c);
      b = b.slice(0, 5);
      obj[b] = c
    })
    return obj
  }
  // 格式化歌曲进度的时间.商是分钟，余是秒数
  formatTime(time) {
    // padStart 字符串的补全方法，padStart是在前面补全，padEnd是在后面补全
    // 第一个参数是补全后有几位，第二个参数是用什么来填充
    let min = String(Math.floor(time/60)).padStart(2, 0);
    let sec = String(Math.floor(time%60)).padStart(2, 0);
    return `${min}:${sec}`
  }
  moveLrc() {
    // 滚动歌词
    let el = document.getElementById('lrc');
    this.setState({
      // 具体滚动的像素要根据样式确定，就是一行歌词的行高
      height: this.state.height - 21
    })
    // 这里是在滚动歌词
    el.style.transform = 'translateY('+this.state.height+'px)'
  }
  playMusic() {
    let audio = this.refs.audio;
    // 判断播放状态
    if (audio.paused) {
      audio.play();
      this.setState({
        isPlay: true
      });
      audio.ontimeupdate = () => {
        let time = audio.currentTime;
        if(this.formatTime(time) in this.state.lyric) {
          // 当前播放进度和歌词中匹配，说明前一句唱完了，该滚动了
          this.moveLrc()
        }
      }
    } else {
      audio.pause()
      this.setState({
        isPlay: false
      })
    }
  }
  render() {
    return (
      <div>
        <Swiper
          spaceBetween={50}
          slidesPerView={3}
          onSlideChange={() => console.log('slide change')}
          onSwiper={(swiper) => console.log(swiper)}
        >
          {
            this.state.imgList.map((item, index) => {
              return (
                <SwiperSlide key={index}>
                  <img src={item.xxx} />
                </SwiperSlide>
              )
            })
          }
        </Swiper>
        <button className={this.state.isPlay ? 'paly' : 'pause'} onClick={() => this.playMusic()}>播放</button>
        <audio ref="audio" src={this.state.songUrl} />
        <div style={{ width: '100%', height: '200px', 'textAlign': 'center' }}>我是一张CD</div>
        <div className="lrc-wrap">
          <div className="lrc-div" id="lrc">
            {
              Object.entries(this.state.lyric).map((item, index) => {
                return (
                  <div key={index}>{item[1]}</div>
                )
              })
            }
          </div>
        </div>
      </div>
    );
  }
}

export default SongDetail;
